package com.example.xymarket.adapter;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;

import com.example.xymarket.activity.HomeActivity;

import java.util.List;


public class MyPagerAdapter extends PagerAdapter {

    private List<HomeActivity.Ad> images;
    private Context context;
    Handler handler;
    public MyPagerAdapter(List<HomeActivity.Ad> images, Context context,Handler handler)
    {
        this.images=images;
        this.context=context;
        this.handler=handler;
    }

    @Override
    public int getCount() {
        return images.size();
    }

    /***
     *比较View和Oject是否同一实例
     * @param view 页面
     * @param object 这个方法instantiateItem返回的结果
     * @return
     */
    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view==object;
    }

    /**
     *释放资源
     * @param container Viewpager
     * @param position 要释放的位置
     * @param object 要释放的页面
     */
    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        //super.destroyItem(container, position, object);
        container.removeView((View)object);
    }

    /**
     *相当于getView方法
     * @param container Viewpager自身
     * @param position 当前实例化位置
     * @return
     */
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        ImageView imageView=images.get(position).imageView;
        container.addView(imageView);//添加到Viewpager中
        imageView.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                Message message=new Message();
                message.obj=images.get(position).id;
                message.what=100;
                handler.sendMessage(message);
            }});
        return imageView;
    }


}
